﻿using System.Collections.Generic;
using ArmyManager.Commands;
using ArmyManager.Items;
using ArmyManager.Strategies;
using ArmyManager.Units;
using System.Linq;

namespace ArmyManager
{
	public class Armory
	{
		private List<Item> _items = new List<Item>();

		public List<Item> Items { get { return _items; } }

		public ICommand DistributeItems(IEnumerable<Unit> units, IVisitorStrategy visitor, IItemDistributionStrategy itemDistributor)
		{
			CommandList commands = new CommandList();
			itemDistributor.Initialize(_items.ToList());
			foreach (Unit unit in visitor.Initialize(units))
			{
				commands.Add(itemDistributor.Distribute(unit));
				if (itemDistributor.IsFinished())
				{
					break;
				}
			}
			ReplaceArmoryItemsCommand replaceCommand = new ReplaceArmoryItemsCommand(this, itemDistributor.RemainingItems);
			replaceCommand.Execute();
			return new CommandList(new ICommand[] { commands, replaceCommand });
		}

		public List<Item> ReplaceItems(List<Item> newItems)
		{
			var oldItems = _items;
			_items = newItems;
			return oldItems;
		}

		public void RemoveItem(Item item)
		{
			_items.Remove(item);
		}

		public void AddItem(Item item)
		{
			_items.Add(item);
		}
	}
}